import React, { ReactText, useRef, useState } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable, { ActionType } from '@ant-design/pro-table';
import { Spin, Tag, Popconfirm, Button, message } from 'antd';
import { getDictList, dictDelete } from '@/services/system/dict';
import { history } from 'umi';
import DictAdd from './components/DictAdd';
import DictEdit from './components/DictEdit';
import { DeleteOutlined } from '@ant-design/icons';

const { CheckableTag } = Tag;

/**
 * 字典管理
 *
 * @author zhangby
 * @date 22/9/20 10:20 am
 */
export default (): React.ReactNode => {
  const [rows, setRows] = useState<ReactText[]>([]);
  const [loading, setLoading] = useState<boolean>(false);

  const ref = useRef<ActionType>();

  // 删除
  const onDelete = async (id: string) => {
    try {
      setLoading(true);
      await dictDelete(id);
      setLoading(false);
      message.success('删除记录成功！');
      // 刷新
      ref.current?.reloadAndRest();
    } catch (e) {
      setLoading(false);
    }
  };

  // 批量删除
  const onBatchDelete = () => {
    if (rows.length === 0) {
      message.error('请选择要操作的记录');
    }
    onDelete(rows.join(','));
  };

  return (
    <>
      <Spin spinning={loading}>
        <PageContainer subTitle="系统字典数据管理">
          <ProTable<API.SysDict>
            actionRef={ref}
            columns={[
              {
                title: '字典名称',
                dataIndex: 'label',
                width: 150,
                render: (_, record) => (
                  <Button
                    type="link"
                    style={{ padding: 0, margin: 0 }}
                    onClick={() =>
                      history.push(
                        `/sys/dict/detail/${record.id}/${record.label} ( ${record.type} )`,
                      )
                    }
                  >
                    {record.label}
                  </Button>
                ),
              },
              {
                title: '字典类型',
                dataIndex: 'type',
                width: 150,
              },
              {
                title: '字典描述',
                dataIndex: 'description',
                width: 150,
                hideInSearch: true,
              },
              {
                title: '排序',
                dataIndex: 'sort',
                width: 80,
                hideInSearch: true,
              },
              {
                title: '创建时间',
                dataIndex: 'createDate',
                width: 150,
                valueType: 'dateTime',
                hideInSearch: true,
                render: (item, _) => <CheckableTag style={{ padding: 0 }}>{item}</CheckableTag>,
              },
              {
                title: '操作',
                dataIndex: 'option',
                valueType: 'option',
                align: 'center',
                width: 150,
                render: (_, record) => (
                  <>
                    <DictEdit dictId={record.id} refresh={() => ref.current?.reload()} />
                    <Popconfirm
                      placement="topRight"
                      title="确定要删除选中的记录吗?"
                      onConfirm={() => onDelete(record.id)}
                      okText="Yes"
                      cancelText="No"
                    >
                      <Button type="primary" shape="circle" danger style={{ marginLeft: 10 }}>
                        <DeleteOutlined />
                      </Button>
                    </Popconfirm>
                  </>
                ),
              },
            ]}
            rowSelection={{
              columnWidth: 20,
              onChange: (selectedRowKeys, _) => setRows(selectedRowKeys),
            }}
            request={(params, sorter, filter) => getDictList({ ...params, sorter, filter })}
            pagination={{
              pageSize: 10,
            }}
            rowKey="id"
            headerTitle="字典数据列表"
            toolBarRender={() => [
              <div key="del">
                {rows.length > 0 ? (
                  <Popconfirm
                    title="确定要删除选中的记录吗?"
                    onConfirm={onBatchDelete}
                    okText="Yes"
                    cancelText="No"
                  >
                    <Button type="primary" danger>
                      <DeleteOutlined />
                      批量删除
                    </Button>
                  </Popconfirm>
                ) : null}
              </div>,
              <DictAdd key="add" refresh={() => ref.current?.reload()} />,
            ]}
          />
        </PageContainer>
      </Spin>
    </>
  );
};
